package com.mmall.service.Impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CartMapper;
import com.mmall.dao.OrderItemMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Cart;
import com.mmall.pojo.Product;
import com.mmall.service.ICartService;
import com.mmall.utils.BigDecimalUtil;
import com.mmall.utils.PropertiesUtil;
import com.mmall.vo.CartProductVo;
import com.mmall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;


@Service("iCartService")
public class CartServiceImpl implements ICartService {


    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    public ServerResponse list(Integer userId) {
        CartVo cartVo = getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }


    public ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count) {
        if (productId == null || count == null || count < 0) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }
        //查询商品是否存在，不存在则添加商品
        Cart cartRet = cartMapper.selectByUserIdProductId(userId, productId);
        if (cartRet == null) {
            //商品不存在，添加一条记录
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setChecked(Const.Cart.CHECKED);
            //设置商品库存
            cart.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cart);

        } else {
            //商品存在，修改数量即可
            count = cartRet.getQuantity() + count;
            cartRet.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cartRet);
        }
        CartVo cartVo = getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    public ServerResponse<CartVo> update(Integer userId, Integer productId, Integer quantity) {
        if (userId == null || quantity == null || productId == null) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }

        Cart cartItem = cartMapper.selectByUserIdProductId(userId, productId);
        if (cartItem != null) {
            Cart cart = new Cart();
            cart.setId(cartItem.getId());
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            //更新库存
            cartMapper.updateByPrimaryKeySelective(cart);
        }

        return this.list(userId);
    }


    public ServerResponse<CartVo> delete(Integer userId, String productIds) {
        //与前端约定，productId以逗号分隔
        List<String> productArr = Splitter.on(",").splitToList(productIds);
        if (CollectionUtils.isEmpty(productArr)) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }
        cartMapper.deleteByUserIdProductIds(userId, productArr);
        return this.list(userId);

    }


    public ServerResponse cartProductCount(Integer userId){
        if(userId==null){
            return ServerResponse.createBySuccess(0);
        }
        int count = cartMapper.selectProductCountByUserId(userId);
        return ServerResponse.createBySuccess(count);
    }


    public ServerResponse<CartVo> selectOrUnSelect(Integer userId,Integer productId,Integer checked){
        if(userId==null||checked==null){
            return ServerResponse.createBySuccess();
        }
        cartMapper.selectOrUnSelect(userId,productId,checked);
        return this.list(userId);
    }


    //根据用户id获得cartVo对象
    //数据封装过程 Product-->CartProductVo-->CartVo
    private CartVo getCartVoLimit(Integer userId) {
        CartVo cartVo = new CartVo();
        List<Cart> carts = cartMapper.selectByUserId(userId);

        List<CartProductVo> cartProductVoList = Lists.newArrayList();

        //初始化总价格为0
        BigDecimal cartTotalPrice = new BigDecimal("0");

        //如果购物车不为空，取出productId封装cartProductVo对象
        if (CollectionUtils.isNotEmpty(carts)) {
            for (Cart cartItem : carts) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setProductId(cartItem.getProductId());
                cartProductVo.setUserId(userId);

                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                if (product != null) {
                    //封装cartProductVo对象
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductPrice(product.getPrice());
                    cartProductVo.setProductTitle(product.getSubtitle());
                    cartProductVo.setProductStock(product.getStock());
                    cartProductVo.setProductStatus(product.getStatus());

                    int buyLimitCount = 0;

                    //判断库存设置数量
                    if (product.getStock() >= cartItem.getQuantity()) {
                        buyLimitCount = cartItem.getQuantity();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    } else {
                        //库存数量不足
                        buyLimitCount = product.getStock();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                    }

                    //设置商品数量和商品价格
                    cartProductVo.setQuantity(buyLimitCount);
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(new Double(buyLimitCount), product.getPrice().doubleValue()));
                    cartProductVo.setProductChecked(cartItem.getChecked());

                }
                //如果商品是选中的，则将商品价格添加到总价当中
                if (Const.Cart.CHECKED == cartItem.getChecked()) {
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        //如果购物车内容为空，不报错，返回空即可
        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setAllChecked(getAllCheckedStatus(userId));
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

        return cartVo;
    }

    private boolean getAllCheckedStatus(Integer userId) {
        if (userId == null) {
            return false;
        }
        //查询为勾选的商品
        return cartMapper.selectCartProductStatusByUserId(userId) == 0;
    }


}
